//
//  RootViewController.m
//  OfficeEtc
//
//  Created by Wangli on 12-6-2.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "RootViewController.h"
#import "FileTableViewController.h"
#import "PhotoMainViewController.h"
#import "AudioMainViewController.h"
#import "VideonMainViewController.h"
#import "MemoMainViewController.h"
#import "SettingViewController.h"
#import "FtpServer.h"
#import "NetworkController.h"
#import "Reachability.h"

@interface UINavigationBar (addbg)
@end
@implementation UINavigationBar (addbg)
- (void)drawRect:(CGRect)rect 
{
    UIImage *img  = [UIImage imageNamed: @"sliverwhite.png"];
    [img drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}


@end

@interface RootViewController ()

@end

@implementation RootViewController
@synthesize m_AudioVC;
@synthesize m_PhotoVC;
-(id) init
{
    if (self = [super init]) 
    {
        self.navigationItem.title = @"我的助手";
        //创建基本的文件结构
        NSArray *docFolders = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES ); 
        NSString* tDocPath = [docFolders lastObject];
        NSArray *libFolders = NSSearchPathForDirectoriesInDomains (NSLibraryDirectory, NSUserDomainMask, YES ); 
        NSString* tlibPath = [libFolders lastObject];
        
        NSString* tWifiFloderPath = [tDocPath stringByAppendingPathComponent:@"wifi-Files"];
        NSFileManager* tFileManager = [NSFileManager defaultManager];
        if (![tFileManager fileExistsAtPath:tWifiFloderPath]) {
            NSError* tError = nil;
            if (![tFileManager createDirectoryAtPath:tWifiFloderPath withIntermediateDirectories:YES attributes:nil error:&tError]) {
                NSLog(@"create wifi floder error = %@",[tError description]);
            }
        }
        
        NSString* tPhotoPath = [tDocPath stringByAppendingPathComponent:@"photo"];
        if (![tFileManager fileExistsAtPath:tPhotoPath]) {
            NSError* tError = nil;
            if (![tFileManager createDirectoryAtPath:tPhotoPath withIntermediateDirectories:YES attributes:nil error:&tError]) {
                NSLog(@"create wifi floder error = %@",[tError description]);
            }
        }
        
        NSString* tMusicFloderPath = [tDocPath stringByAppendingPathComponent:@"music"];
        if (![tFileManager fileExistsAtPath:tMusicFloderPath]) {
            NSError* tError = nil;
            if (![tFileManager createDirectoryAtPath:tMusicFloderPath withIntermediateDirectories:YES attributes:nil error:&tError]) {
                NSLog(@"create wifi floder error = %@",[tError description]);
            }
        }
        
        NSString* tThumFloderPath = [tlibPath stringByAppendingPathComponent:@"Thumbnail"];
        if (![tFileManager fileExistsAtPath:tThumFloderPath]) {
            NSError* tError = nil;
            if (![tFileManager createDirectoryAtPath:tThumFloderPath withIntermediateDirectories:YES attributes:nil error:&tError]) {
                NSLog(@"create tThumFloderPath floder error = %@",[tError description]);
            }
        }
        
        p_FileImgDic = [NSDictionary dictionaryWithObjectsAndKeys:
                        [UIImage imageNamed:@"zip.png"],@"zip",
                        [UIImage imageNamed:@"doc.png"],@"doc",
                        [UIImage imageNamed:@"aperture.png"],@"pic",
                        [UIImage imageNamed:@"shadow.png"],@"fil",
                        nil];
        
        [p_FileImgDic retain];
        
        if (m_AudioVC == nil) {
            m_AudioVC = [[AudioMainViewController alloc] init];
        }
        if (m_PhotoVC == nil) {
            m_PhotoVC = [[PhotoMainViewController alloc] init];
        }
    }
    return self;
}
-(void) dealloc{
    [super dealloc];
    [m_AudioVC release];
    [m_PhotoVC release];
    [self stopFtpServer];
    [p_theServer release];
    p_theServer =nil;
    [p_FileImgDic release];
    [p_PhotoPath release];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    if([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"sliverwhite.png"] forBarMetrics: UIBarMetricsDefault];
        self.navigationController.navigationBar.clipsToBounds = YES;
        
    }
    //文档，照片，音频，视频，便签，设置
    NSArray* tMainButtonArr = [NSArray arrayWithObjects:@"文档",@"照片",@"音频"
                               ,@"视频",@"便签",@"设置",nil];
    int tIndex = 0;
    for (NSString* tStrBtt in tMainButtonArr) {
        UIButton* tMainBtt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [tMainBtt setTitle:tStrBtt forState:UIControlStateNormal];
        tMainBtt.frame =CGRectMake(28+(tIndex%2)*150, 16+(tIndex/2)*140, 110, 100);
        tMainBtt.tag =10+tIndex;
        [tMainBtt addTarget:self action:@selector(pressedMainButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:tMainBtt];
        tIndex++;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}
#pragma mark-
#pragma mark 类私有功能函数
//主菜单按钮回调
-(void) pressedMainButton:(UIButton*) f_sender
{
    int tBtTag = f_sender.tag-10;
    UIViewController* tNextVController = nil;
    switch (tBtTag) {
        case 0:
        {
            tNextVController = [[[FileTableViewController alloc] init] autorelease];
            tNextVController.title =@"我的文档";
            ((FileTableViewController*)tNextVController).m_OprEditMode = ItemOperNoneMode;
            ((FileTableViewController*)tNextVController).m_FileImgDic = p_FileImgDic;
            NSArray *docFolders = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES ); 
            NSString* tDocPath = [docFolders lastObject];
            ((FileTableViewController*)tNextVController).m_CurrentPath = tDocPath;
        }
            break;
        case 1:
        {
            tNextVController = m_PhotoVC;
            tNextVController.title =@"我的照片";
        }
            break;
        case 2:
        {
            tNextVController =m_AudioVC;
            tNextVController.title =@"我的音频";
        }
            break;
        case 3:
        {
            tNextVController = [[[VideonMainViewController alloc] init] autorelease];
            tNextVController.title =@"我的视频";
        }
            break;
        case 4:
        {
            tNextVController = [[[MemoMainViewController alloc] init] autorelease];
            tNextVController.title =@"我的便签";
        }
            break;
        case 5:
        {
            tNextVController = [[[SettingViewController alloc] init] autorelease];
            tNextVController.title =@"设置";
        }
            break;
    }
    [self.navigationController pushViewController:tNextVController animated:YES];
}


#pragma mark-
#pragma mark UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    
}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
  
}

/// 网络是否是通的
- (BOOL)networkAvailable {
    Reachability *r = [Reachability reachabilityForInternetConnection];
    int tStatus = [r currentReachabilityStatus];
    if (tStatus == kReachableViaWiFi) {
        return YES;
    }
    return NO;
}

#pragma mark-
#pragma mark FTPServer
-(void) FTPServerShow:(NSString*)f_StrPath
{
    if (![self networkAvailable]) {
        UIAlertView* tAlertWifi = [[UIAlertView alloc] initWithTitle:@"友情提示" message:@"没有检测到wifi信号请稍后再试！" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles: nil];
        [tAlertWifi show];
        [tAlertWifi release];
        return;
    }
    NSString *localIPAddress = [NetworkController localWifiIPAddress];
    NSString *alertTitle = [NSString stringWithFormat:@"%@ %@ %@", @"Connect to", localIPAddress, @"port 20000"];	
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertTitle 
                                                    message:@"The FTP Server has been enabled, please use FTP client software to transfer any import/export data to or from this device.  Press the \"Stop FTP Server\" button once all data transfers have been completed."
                                                   delegate:self 
                                          cancelButtonTitle:@"Stop FTP Server" 
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
    
	if (p_theServer) {
        [self stopFtpServer];
        [p_theServer release];
        p_theServer =nil;
    }
    p_theServer = [[ FtpServer alloc ] initWithPort:20000 withDir:f_StrPath notifyObject:self ];
}


- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex 
{
    
	if (buttonIndex == 0) {
		[alert dismissWithClickedButtonIndex:0 animated:YES];
		[self stopFtpServer];
	} 
}


- (void)stopFtpServer 
{
	NSLog(@"Stopping the FTP server");
	if(p_theServer)
	{
		[p_theServer stopFtpServer];
		[p_theServer release];
		p_theServer=nil;
	}
}

-(void)didReceiveFileListChanged:(NSString*)f_Path Status:(NSInteger)f_Status oldName:(NSString*) f_OldName
{
    if ([f_Path rangeOfString:m_PhotoVC.m_PhotoPath].location != NSNotFound) {
        //图片那刷新下
        if(f_Status ==-1){
            //删除文件
            [m_PhotoVC delFileByFTP:f_Path];
        }else if(f_Status == 1){
            //添加
            [m_PhotoVC addFileByFTP:f_Path];
        }else {
            //重命名
            [m_PhotoVC reNameFileByFTP:f_Path oldName:f_OldName];
        }
        NSObject* tObjectVC = [[self.navigationController viewControllers] lastObject];
        if ([tObjectVC isKindOfClass:[FileTableViewController class]]) {
            if(f_Status ==-1){
                //删除文件
                [tObjectVC performSelector:@selector(delFileByFTP:) withObject:nil];
            }else if(f_Status == 1){
                //添加
                [tObjectVC performSelector:@selector(addFileByFTP:) withObject:nil];
            }else {
                //重命名
                [tObjectVC performSelector:@selector(reNameFileByFTP:oldName:) withObject:nil];
            }
        }
    }else if ([f_Path rangeOfString:m_AudioVC.m_MusicPath].location != NSNotFound) {
        //音乐那刷新下
        if(f_Status ==-1){
            //删除文件
            [m_AudioVC delFileByFTP:f_Path];
        }else if(f_Status == 1){
            //添加
            [m_AudioVC addFileByFTP:f_Path];
        }else {
            //重命名
            [m_AudioVC reNameFileByFTP:f_Path oldName:f_OldName];
        }
        NSObject* tObjectVC = [[self.navigationController viewControllers] lastObject];
        if ([tObjectVC isKindOfClass:[FileTableViewController class]]) {
            if(f_Status ==-1){
                //删除文件
                [tObjectVC performSelector:@selector(delFileByFTP:) withObject:nil];
            }else if(f_Status == 1){
                //添加
                [tObjectVC performSelector:@selector(addFileByFTP:) withObject:nil];
            }else {
                //重命名
                [tObjectVC performSelector:@selector(reNameFileByFTP:oldName:) withObject:nil];
            }
        }
    }else {
        NSObject* tObjectVC = [[self.navigationController viewControllers] lastObject];
        if(f_Status ==-1){
            //删除文件
            if ([tObjectVC respondsToSelector:@selector(delFileByFTP:)]) {
                [tObjectVC performSelector:@selector(delFileByFTP:) withObject:f_Path];
            }else {
                NSLog(@"delete file by ftp not responder");
            }
        }else if(f_Status == 1){
            //添加
            if ([tObjectVC respondsToSelector:@selector(addFileByFTP:)]) {
                [tObjectVC performSelector:@selector(addFileByFTP:) withObject:f_Path];
            }else {
                NSLog(@"add file by ftp not responder");
            }
        }else {
            //重命名
            if ([tObjectVC respondsToSelector:@selector(reNameFileByFTP:oldName:)]) {
                [tObjectVC reNameFileByFTP:f_Path oldName:f_OldName];
            }else {
                NSLog(@"rename file by ftp not responder");
            }
        }
    }
}

@end
